package com.munhrasoft.dinamica.business.logic;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.munhrasoft.dinamica.business.entities.GroupEntity;
import com.munhrasoft.dinamica.business.entities.UserEntity;

@Stateless
public class UserEJB {

    @PersistenceContext(unitName = "dinamicaPU")
    private EntityManager em;

    @SuppressWarnings("unchecked")
    public List<UserEntity> fetchAllUsuarios() {
        Query query = em.createNamedQuery("findAllAuthUsr");
        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    public List<GroupEntity> fetchAllGrupos() {
        Query query = em.createNamedQuery("findAllGroupEntity");
        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    public List<GroupEntity> findGroupByName(String groupName) {
        Query query = em.createNamedQuery("findByGroupName");
        query.setParameter("name", groupName.toLowerCase() + "%");
        return query.getResultList();
    }

    public UserEntity createUsuario(UserEntity usuario) {
        em.persist(usuario);
        return usuario;
    }

    public UserEntity updateUsuario(UserEntity usuario) {
        return em.merge(usuario);
    }

    public void removeUsuario(UserEntity usuario) {
        // TODO Nao pode deixar remover o admin, tem sempre que sobrar ele
        em.remove(em.merge(usuario));
    }

}
